package api

import (
	"net/http"

	"fmt"
	"html/template"
	"io/ioutil"
	"os"
	"path"
	"strings"

	"gitee.com/DengAnbang/Computation/src/bean"
	"gitee.com/DengAnbang/Computation/src/code"
	"gitee.com/DengAnbang/Computation/src/dbops"
	"gitee.com/DengAnbang/goutils/sysUtils"
	"gitee.com/DengAnbang/goutils/utils"

	"gitee.com/DengAnbang/goutils/fileUtil"
	"gitee.com/DengAnbang/goutils/loge"
)

func LogSwitch(w http.ResponseWriter, r *http.Request) error {
	if loge.IsDebug {
		fmt.Fprint(w, "关闭调试日志")
	} else {
		fmt.Fprint(w, "打开调试日志")
	}
	loge.IsDebug = !loge.IsDebug
	return nil
}
func DatabaseBackups(w http.ResponseWriter, r *http.Request) error {
	s, err := dbops.DatabaseBackupsHttp()
	if err != nil {
		return err
	}
	//w.Header().Set("Content-Type", "application/zip")
	w.Header().Set("Content-Disposition", "attachment; filename="+path.Base(s))
	http.ServeFile(w, r, s)
	return nil
}
func ClearRedundantData(w http.ResponseWriter, r *http.Request) error {
	err := dbops.ClearRedundantData()
	if err != nil {
		return err
	}
	return bean.NewSucceedMessage("成功")
}

func SysRestart(w http.ResponseWriter, r *http.Request) error {
	service, err := sysUtils.GetService("算量平台服务")
	if err != nil {
		return err
	}
	err = service.Stop()
	if err != nil {
		return err
	}
	err = service.Start()
	if err != nil {
		return err
	}
	return bean.NewSucceedMessage("成功")
}
func DatabaseRestore(w http.ResponseWriter, r *http.Request) error {
	if r.Method == "GET" {
		html := `<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Upload</title>
</head>
<body>
<form method="POST" action="/public/database/restore" enctype="multipart/form-data">
    选择备份文件: <input name="file" type="file" />
    <input type="submit" value="上传" />
</form>
</body>
</html>`
		fmt.Fprint(w, html)
		return nil
	} else {
		file, h, err := r.FormFile("file")
		if err != nil {
			return err
		}
		bytes, err := ioutil.ReadAll(file)
		if err != nil {
			return err
		}
		resName := code.DatabaseRootPath + "up" + h.Filename

		os.MkdirAll(path.Dir(resName), 0x666)

		err = ioutil.WriteFile(resName, bytes, 0x666)
		if err != nil {
			return err
		}
		err = dbops.DatabaseRestoreHttp(resName)
		if err != nil {
			return err
		}

		return bean.NewSucceedMessage("成功")
	}

}
func AuthenticationLicPC(w http.ResponseWriter, r *http.Request) error {
	fileName := code.ConfigRootPath + code.PCLinName
	if !fileUtil.PathExists(fileName) {
		return bean.NewErrorMessage("图形核心的lic不存在!")
	}
	bytes, err := ioutil.ReadFile(fileName)
	if err != nil {
		return err
	}
	return bean.NewSucceedMessage(string(bytes))
}
func FileUpload(w http.ResponseWriter, r *http.Request) error {
	if r.Method == "GET" {
		t, err := template.ParseFiles(code.ViewRootPath + "upload.html")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return err
		}
		t.Execute(w, nil)
		return nil
	} else if r.Method == "POST" {
		file, h, err := r.FormFile("file")
		if err != nil {
			message := bean.NewErrorMessage("文件上传失败!")
			message.DebugMessage = err.Error()
			return message
		}
		bytes, err := ioutil.ReadAll(file)
		if err != nil {
			return err
		}
		fileParent := code.FileRootPath + strings.Replace(path.Ext(h.Filename), ".", "", 1) + "/" + utils.NewUUID() + "/"
		os.MkdirAll(fileParent, 0x666)
		resName := fileParent + h.Filename
		err = ioutil.WriteFile(resName, bytes, 0x666)
		if err != nil {
			return err
		}
		resName = strings.Replace(resName, code.CurrentPath, "", 1)
		return bean.NewSucceedMessage(resName)
	} else {
		return bean.NewErrorMessage("只支持POST的上传方式!")
	}
	return nil
}
